<template>
  <div class="import-container">
    <el-dialog
      title="批量编辑安装信息"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="closeAddDialog"
      :append-to-body="true"
      :close-on-click-modal="false"
    >
      <div class="mini-dialog">
        <h3 class="title" style="margin-top: 5px">导入文件编辑注意事项：</h3>
        <div class="import-item">
          1、 请先下载批量导入模板，再进行批量上传操作。
        </div>
        <div class="import-item">
          2、
          请在对应单元格填写建筑物名称、楼层名称、安装点名称等。设备编码不可修改。
        </div>
        <div class="import-item">
          3、 不选择组织机构则默认导出所有租户信息。
        </div>
        <!-- <div class="import-item">
          2、可只填写组织机构，组织机构监管类型，组织机构详细地址单元格等必填字段进行批量新增组织机构操作。
        </div> -->
      </div>

      <el-form
        :inline="true"
        :model="addInfo"
        class="demo-form-inline"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item
          style="width: 33%"
        >
          <TreeSearch
            style="width: 100%"
            ref="refTreeSearch"
            typeInfo="1,2,3,4"
            @changeOrgId="changeOrgId"
            :appendToBody="true"
          ></TreeSearch>
        </el-form-item>

        <el-form-item style="width: 33%; text-align: right; margin-right: 20px">
          <el-select
            v-model="buildingsName"
            filterable
            placeholder="请选择建筑物"
            v-loadMore="loadMore2"
            clearable
            remote
            :remote-method="remoteMethod2"
            @clear="clearBuildings"
            @change="changebuildings"
          >
            <el-option
              v-for="item in buildings"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
            <div
              class="div_box"
              v-loading="loading2"
              :style="loading2 ? '' : 'display: none;'"
            ></div>
          </el-select>
        </el-form-item>

        <el-form-item style="margin-right: 20px">
          <el-button size="small" type="info" @click="handleDownload">
            下载模板
          </el-button>
        </el-form-item>
      </el-form>

      <div class="content">
        <div>
          <div class="btn-row">
            <el-upload
              ref="upload"
              action="#"
              :limit="1"
              accept=".xls,.xlsx"
              :multiple="false"
              :before-upload="beforeUpload"
              :on-change="handChange"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :auto-upload="false"
              :http-request="uploadRequest"
            >
              <el-button slot="trigger" size="small" type="primary">
                选取文件
              </el-button>

              <div class="el-upload__tip" slot="tip">
                只能上传Excel文件，且不超过500kb
              </div>
            </el-upload>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button
          slot="trigger"
          size="small"
          type="primary"
          @click="importStart"
        >
          开始导入
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqSpaceImport,
  reqOrgList,
  reqSpaceManager,
  reqSpaceTask,
  reqSpaceTaskImport,
} from "@api/api";
import { mapState } from "vuex";
import $ from "jquery";
import loadMore from "@mixin/loadMore";
import TreeSearch from "@components/TreeSearch.vue";

export default {
  name: "importDevice",
  props: ["getLocationInfo", "getAddressflag"],
  mixins: [loadMore],
  components: {
    TreeSearch,
  },
  data() {
    return {
      dialogVisible: false,
      isXlsx: true,
      /* mini弹框 */
      addInfo: {
        orgId: "",
        buildingId: "",
      },
      buildings: [],
      loading: false,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      loading2: false,
      rules: {
        orgId: [
          {
            required: true,
            message: "请选择组织机构",
            trigger: ["blur", "change"],
          },
        ],
      },
      fileName: false,
      buildingsName: "",
      buildingsName2: "",
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    // dialogVisible(e){
    //   if(e){
    //     this.$nextTick(()=>{
    //       this.$refs.refTreeSearch.getDataList()
    //     })
    //   }
    // }
  },
  methods: {
    changeOrgId(instanceId) {
      this.addInfo.orgId = instanceId.id;
      this.clearBuildings();
    },
    // 根据组织机构查询建筑物
    async projectchange(e) {
      // console.log(e);
      // 清空
      this.buildingsName = "";
      this.buildingsName2 = "";
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.addInfo.buildingId = "";
      this.buildings = [];
      if (e == "") return;
      await this.getBuildings();
    },
    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.getBuildings();
      this.loading2 = false;
    },
    // 建筑物列表
    async getBuildings() {
      let res = await reqSpaceManager(this.sysInstanceIndex2, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        metaCode: 1,
        orgId: this.addInfo.orgId,
        isStatistics: 0,
        name: this.buildingsName2,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages2 = res.data.total;
      this.buildings = [...this.buildings, ...res.data.rows];
    },
    // 清空建筑物
    clearBuildings() {
      this.buildingsName = "";
      this.buildingsName2 = "";
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = [];
      this.getBuildings();
    },
    // 远程搜索
    async remoteMethod2(query) {
      if (this.addInfo.orgId == "") return;
      this.buildingsName = query; //保留输入的值
      this.buildingsName2 = query; //保留输入的值
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.buildings = [];
      this.getBuildings();
    },
    // 选择建筑物
    changebuildings(e) {
      this.addInfo.buildingId = e;
    },
    // 上传前验证
    beforeUpload(file) {
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" || Xls[1] !== "xlsx") {
        this.isXlsx = false;
      }
    },
    // 因为 before-upload 是指在文件上传之前、文件已被选中，但还没上传的时候触发，而设置了 :auto-upload=“false” 后，文件上传事件不被再次调用，所以 before-upload 不生效，所以，限制大小的时候，需绑定在 :on-change 里面
    handChange(file) {
      const limitSize = file.size / 1024 / 1024;
      if (limitSize > 0.5) {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("上传文件大小不能超过 500KB!");
        return false;
      }
      let Xls = file.name.split(".");
      if (Xls[1] !== "xls" && Xls[1] !== "xlsx") {
        this.$refs.upload.clearFiles();
        this.$modal.notifyWarning("只能上传Excel文件!");
      }
      this.fileName = true;
    },
    handleRemove(file) {
      this.fileName = false;
    },
    handleExceed() {
      this.$modal.notifyWarning(`当前限制选择 1 个文件`);
    },
    // 正式上传
    importStart() {
      // 检查是否有文件被选择
      if (this.fileName) {
        this.$refs.upload.submit();
      } else {
        this.$modal.notifyWarning("请选取文件上传！");
      }
    },
    // 自定义上传
    async uploadRequest(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      // formData.append("userId", this.user.userId);
      const loading = this.$loading({
        lock: true,
        text: "正在导入，请耐心等待~",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.7)",
      });
      const res = await reqSpaceTaskImport(formData);
      loading.close();
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      setTimeout(() => {
        this.closeAddDialog();
        this.$modal.notifySuccess("批量编辑成功");
        this.$parent.SpaceManager();
      }, 500);
    },
    // 下载模板
    async handleDownload() {
      // if (!this.addInfo.orgId)
      //   return this.$modal.notifyWarning("请选择组织机构");
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // if (this.addInfo.orgId == '') return this.$modal.notifyWarning('请选择组织机构');
          let name = "";
          // this.projectList.forEach((item) => {
          //   if (item.id == this.addInfo.orgId) {
          //     name = item.orgName;
          //     return;
          //   }
          // });
          if (this.addInfo.buildingId != "") {
            this.buildings.forEach((item) => {
              if (item.id == this.addInfo.buildingId) {
                name += "-" + item.name;
                return;
              }
            });
          }
          if (name == "") {
            // 租户名称
            name = this.user.tenantName;
          }
          // if((this.user.roleName == 'ORG_ADMIN' || this.user.roleName == 'INSTERALL_USER')&& this.addInfo.orgId=='') return  this.$modal.notifyWarning('请选择组织机构');
          var res = await reqSpaceTask({
            userId: this.user.userId,
            roleName: this.user.roleName,
            tenantId: this.user.tenantId,
            taskName: name + "安装信息修改导出",
            orgId: this.addInfo.orgId,
            buildingId: this.addInfo.buildingId,
          });
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
          this.$modal.notifySuccess("下载成功");
          this.closeAddDialog();
          this.$router.push({ name: "exportTask" });
        }
      });
    },

    // 点击关闭大弹框
    closeAddDialog() {
      // this.buildings = [];
      // this.sysInstanceIndex2 = 1;
      // this.sysInstanceTotalPages2 = 10;
      // this.buildingsName = "";
      // this.buildingsName2 = "";
      this.addInfo = {
        orgId: "",
        buildingId: "",
      };
      this.fileName = false;
      this.$refs.upload.clearFiles();
      this.$refs.ruleForm.resetFields();
      this.dialogVisible = false;
    },
  },
  deactivated() {
    if (this.$refs.upload != null || this.$refs.ruleForm != null) {
      this.closeAddDialog();
    }
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/common.less");
@import url("~@views/style/tablePage.less");

.mini-dialog {
  margin: 10px 0 20px 24px;
  color: @primaryThemeTxtColor;
}
.el-upload__tip {
  color: @primaryThemeTxtColor;
}

.content {
  padding-left: 21px;
  width: 350px;
  position: relative;
  top: 0;
  bottom: 0;
  left: 20px;
  right: 0;

  // 按钮行
  .btn-row {
    .el-button {
      margin-right: 20px;
    }
  }
}

/* mini弹框 */
.title {
  line-height: 30px;
}

.import-item {
  line-height: 24px;
}

::v-deep .el-collapse {
  border: none;
}

::v-deep .el-icon-arrow-right {
  color: @primaryThemeTxtColor;
}

::v-deep .el-input__inner {
  height: 32px !important;
}

form {
  padding-left: 40px !important;
}

.zuobiao {
  color: @primaryTxtcolor !important;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
  margin-right: 0px;
}

.mapLoc {
  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}

.demo-form-inline {
  display: flex;
  justify-content: space-between;
  margin-bottom: 3px;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 100%;
  z-index: 2016;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

::v-deep .el-form-item__content {
  // line-height: 0;
}
</style>
